package com.mobile.framework.util;

import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * MailManager
 */
public class MailManager {
	private static Log log = LogFactory.getLog(MailManager.class);

	public static void sendMail(String title, String body, String to) {
		sendMail(title, body, to, Config.getProperty("mail.sender.from"));
	}

	public static void sendMail(String title, String body, String to,
			String from) {
		try {
			String host = Config.getProperty("mail.smtp.host");
			String username = Config.getProperty("mail.smtp.username");
			String password = Config.getProperty("mail.smtp.password");
			Properties p = new Properties();
			p.put("mail.smtp.host", host);
			p.put("mail.smtp.auth", Config
					.getProperty("mail.smtp.host", "true"));

			Session session = Session.getDefaultInstance(p, null); // 获得邮件会话对象

			MimeMessage mimeMsg = new MimeMessage(session); // 创建MIME邮件
			mimeMsg.setSubject(title);// 标题

			// 创建内容
			MimeMultipart mp = new MimeMultipart();
			BodyPart bp = new MimeBodyPart();
			bp.setContent(body, "text/plain;charset=GB2312");
			// 加附件
			/*
			 * FileDataSource fileds = new FileDataSource(filename);
			 * bp.setDataHandler(new DataHandler(fileds));
			 * bp.setFileName(fileds.getName());
			 */
			mp.addBodyPart(bp);

			mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
					.parse(to));

			// mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();

			Transport transport = session.getTransport("smtp");
			transport.connect(host, username, password);
			transport.sendMessage(mimeMsg, mimeMsg
					.getRecipients(Message.RecipientType.TO));
			// transport.send(mimeMsg);
			transport.close();
		} catch (Exception e) {
			log.error("sendMail error:" + e, e);
		}
	}

}
